import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.control.ToolBar;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaException;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;
import java.net.URI;
import java.nio.file.Paths;

public class JPlayer extends Application {
    String iconSrc = "img/icon.png";
    String mediaTitle = "JPlayer";

    private MediaPlayer mediaPlayer;
    private MediaView mediaView;
    private Slider progressSlider;

    @Override
    public void start(Stage primaryStage) {
        // Create the media player and its view
        mediaView = new MediaView();
        StackPane pane = new StackPane(mediaView);

        // Create the toolbar
        ToolBar toolBar = new ToolBar();

        // Create the open button
        Button openButton = new Button("打开");
        openButton.setFocusTraversable(false);
        openButton.setOnAction(event -> openFile());
        toolBar.getItems().add(openButton);

        // Create the play button
        Button playButton = new Button("开始");
        playButton.setFocusTraversable(false);
        playButton.setOnAction(event -> mediaPlayer.play());
        toolBar.getItems().add(playButton);

        // Create the pause button
        Button pauseButton = new Button("暂停");
        pauseButton.setFocusTraversable(false);
        pauseButton.setOnAction(event -> mediaPlayer.pause());
        toolBar.getItems().add(pauseButton);

        // Create the stop button
        Button stopButton = new Button("停止");
        stopButton.setFocusTraversable(false);
        stopButton.setOnAction(event -> mediaPlayer.stop());

        toolBar.getItems().add(stopButton);

        // Create the fullscreen button
        Button fullscreenButton = new Button("全屏");
        fullscreenButton.setFocusTraversable(false);

        fullscreenButton.setOnAction(event -> {
            Scene scene = primaryStage.getScene();
            if (scene != null) {
                primaryStage.setFullScreen(!primaryStage.isFullScreen());
                Stage stage = (Stage) fullscreenButton.getScene().getWindow();
                //If full screen, hide the toolbar and progress bar
                if (stage.isFullScreen()) {
                    toolBar.setVisible(false);
                    progressSlider.setVisible(false);
                    //Otherwise, the toolbar and progress bar are displayed
                } else {
                    toolBar.setVisible(true);
                    progressSlider.setVisible(true);
                }
            }

        });
        toolBar.getItems().add(fullscreenButton);

        // Set the toolbar at the top of the border pane
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(toolBar);

        // Create the progress slider
        progressSlider = new Slider(0.0, 1.0, 0.0);
        progressSlider.setFocusTraversable(false);
        progressSlider.valueProperty().addListener(event -> {
            if (mediaPlayer != null && progressSlider.isValueChanging()) {
                mediaPlayer.seek(mediaPlayer.getTotalDuration().multiply(progressSlider.getValue()));
            }
        });
        // Add mouse click listener for progress slider
        progressSlider.setOnMouseClicked(event -> {
            if (event.getButton() == MouseButton.PRIMARY && mediaPlayer != null) {
                double pos = event.getX() / progressSlider.getWidth();
                mediaPlayer.seek(mediaPlayer.getTotalDuration().multiply(pos));
            }
        });

        // Create the VBox for the media view and progress slider
        VBox vBox = new VBox();
        vBox.getChildren().addAll(pane, progressSlider);
        // Set a 20-pixel padding at the bottom
        vBox.setPadding(new Insets(0, 0, 20, 0));
        borderPane.setCenter(vBox);

        // Create the scene
        Scene scene = new Scene(borderPane, 640, 480);
        scene.setOnKeyPressed(event -> {

            if (event.getCode() == KeyCode.SPACE && mediaPlayer != null) {
                if (mediaPlayer.getStatus() == MediaPlayer.Status.PLAYING) {
                    mediaPlayer.pause();
                } else {
                    mediaPlayer.play();
                }
            }

            //f11
            if (event.getCode() == KeyCode.F11 && mediaPlayer != null) {
                primaryStage.setFullScreen(!primaryStage.isFullScreen());
                Stage stage = (Stage) fullscreenButton.getScene().getWindow();
                if (stage.isFullScreen()) {
                    toolBar.setVisible(false);
                    progressSlider.setVisible(false);
                } else {
                    toolBar.setVisible(true);
                    progressSlider.setVisible(true);
                }
            }

            if (mediaPlayer != null) {
                switch (event.getCode()) {
                    case UP: // Press the up button to raise the volume
                        mediaPlayer.setVolume(Math.min(mediaPlayer.getVolume() + 0.05, 1.0));
                        break;
                    case DOWN: // Press the button to lower the volume
                        mediaPlayer.setVolume(Math.max(mediaPlayer.getVolume() - 0.05, 0.0));
                        break;
                    case LEFT: // Press the left button to fast-forward 10 seconds
                        mediaPlayer.seek(mediaPlayer.getCurrentTime().subtract(Duration.seconds(10.0)));
                        break;
                    case RIGHT: // 按右键向前快进10秒
                        mediaPlayer.seek(mediaPlayer.getCurrentTime().add(Duration.seconds(10.0)));
                        break;
                    default:
                        break;
                }
            }
        });

        primaryStage.setScene(scene);

        primaryStage.fullScreenProperty().addListener((observableValue, oldValue, newValue) -> {
            if (!newValue) { //Exit the full screen to display the toolbar
                toolBar.setVisible(true);
                progressSlider.setVisible(true);
            }

        });


        // Bind the width and height of the root stack pane to the scene width and height
        pane.prefWidthProperty().bind(scene.widthProperty());
        pane.prefHeightProperty().bind(scene.heightProperty());

        // Bind the width of the progress slider to the width of the VBox
        progressSlider.prefWidthProperty().bind(vBox.widthProperty());

        // Bind the width and height of the media view to the scene width and height
        mediaView.fitWidthProperty().bind(scene.widthProperty());
        mediaView.fitHeightProperty().bind(scene.heightProperty());

        // Create the primary stage
        primaryStage.setTitle(mediaTitle);
        primaryStage.getIcons().add(new Image(iconSrc));
        primaryStage.show();
    }

    private void openFile() {
        // Create a file chooser dialog
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("打开视频文件");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("视频文件", "*.mp4"));

        // Show the dialog and get the selected file
        File file = fileChooser.showOpenDialog(null);

        // If a file was selected, load it into the media player
        if (file != null) {
            try {
                URI uri = Paths.get(file.getAbsolutePath()).toUri();
                Media media = new Media(uri.toString());
                if (mediaPlayer != null) {
                    mediaPlayer.dispose();
                }
                mediaPlayer = new MediaPlayer(media);
                mediaView.setMediaPlayer(mediaPlayer);

                // Bind the progress slider to the current time of the media player
                mediaPlayer.currentTimeProperty().addListener(event -> {
                    if (!progressSlider.isValueChanging()) {
                        double currentTime = mediaPlayer.getCurrentTime().toMillis();
                        double duration = mediaPlayer.getTotalDuration().toMillis();
                        progressSlider.setValue(currentTime / duration);
                    }
                });

                // Update the title of the window with the name of the video file
                mediaTitle = "JPlayer - " + file.getName();
                ((Stage) mediaView.getScene().getWindow()).setTitle(mediaTitle);

            } catch (MediaException e) {
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setTitle("错误");
                alert.setHeaderText("无法打开文件");
                alert.setContentText("打开文件时发生错误。");
                alert.showAndWait();
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}
